#!/usr/bin/python3
# -*- encoding: utf-8 -*-
"""
@File    : serializers.py
@Time    : 2022/6/1 17:44
@Author  : YangXin
@License : Copyright(C) 2022 忆享科技 All rights reserved
@Desc    :
"""
from blueapps.utils import get_client_by_request
from rest_framework import serializers

from home_application.celery_tasks import get_task_status
from home_application.models import TaskRecord


class TaskRecordSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = TaskRecord
        fields = ("id", "task_name", "task_id", "biz_id", "tpl_id", "status", "creator", "create_time")


class TaskSerializer(serializers.Serializer):
    biz_id = serializers.IntegerField(label="业务id")
    tpl_id = serializers.IntegerField(label="模板id")
    task_name = serializers.CharField(label="任务名称", max_length=10, min_length=3)
    params = serializers.ListField(label="模板参数", write_only=True)
    tpl_name = serializers.CharField(label="模板名称", max_length=100, min_length=1)

    def create_task(self):
        tpl_params = self.validated_data["params"]
        constants = {}
        for item in tpl_params:
            constants[item["key"]] = int(item["value"]) if item["type"] == "int" else item["value"]
        kwargs = {
            "name": self.validated_data["task_name"],
            "bk_biz_id": str(self.validated_data["biz_id"]),
            "template_id": str(self.validated_data["tpl_id"]),
            "constants": constants
        }
        client = get_client_by_request(self.context["request"])
        return client.sops.create_task(kwargs)

    def start_task(self, task_id):
        kwargs = {
            "bk_biz_id": str(self.validated_data["biz_id"]),
            "task_id": task_id,
        }
        client = get_client_by_request(self.context["request"])
        return client.sops.start_task(kwargs)

    def create(self, validated_data):
        token = self.context["request"].COOKIES.get("bk_token")
        res = self.create_task()
        if res.get("code") != 0:
            raise serializers.ValidationError(res.get("message"))
        q = TaskRecord.objects.create(
            **{
                "task_name": validated_data["task_name"],
                "biz_id": validated_data["biz_id"],
                "tpl_id": validated_data["tpl_id"],
                "tpl_name": validated_data["tpl_name"],
                "task_id": res["data"]["task_id"],
                "task_url": res["data"]["task_url"],
                "creator": self.context["request"].user.username
            }
        )
        self.start_task(q.task_id)
        get_task_status.apply_async(args=(token, q.biz_id, q.task_id))
        return q



